package com.wave.redis.config;

import com.wave.redis.util.RedisUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author 夕下风波
 * @date 2025-02-23 14:49
 * @description
 */
@Configuration
@EnableConfigurationProperties(WaveRedisConfig.class)
@ConditionalOnClass(RedisUtil.class)
public class WaveRedisAutoConfiguration {

    private final WaveRedisConfig waveRedisConfig;

    public WaveRedisAutoConfiguration(WaveRedisConfig waveRedisConfig) {
        this.waveRedisConfig = waveRedisConfig;
    }

    // 配置 RedisConnectionFactory
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisConnectConfig = new RedisStandaloneConfiguration();
        redisConnectConfig.setHostName(waveRedisConfig.getHost());
        redisConnectConfig.setPort(waveRedisConfig.getPort());
        redisConnectConfig.setPassword(RedisPassword.of(waveRedisConfig.getPassword()));
        redisConnectConfig.setDatabase(waveRedisConfig.getDatabase());
        return new LettuceConnectionFactory(redisConnectConfig);
    }

    // 配置 RedisTemplate
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

    // 注入 RedisUtil
    @Bean
    public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
        return new RedisUtil(redisTemplate);
    }
}